package com.qubaopen.core.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
//import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.qubaopen.core.common.CoreConstants;
import com.qubaopen.core.utils.RegexUtils;

//导入三个常量

/**
 * 检查Session是否超时的过滤器
 * 
 * @author ZhangYongYi
 * 
 */
// Filter接口要实现：init,dofilter,destroy
public class AuthenticateFitler implements Filter {

	protected FilterConfig filterConfig = null;

	private List<String> notCheckURLList = new ArrayList<String>();

	private String uri = null;

	/**
	 * 过滤处理,notCheckURLList列表之外的所有.htm请求都要进行Session是否超时的处理
	 */
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		HttpSession session = request.getSession(true);

		Object username = session.getAttribute(CoreConstants.SESSION_USERNAME);
		uri = request.getServletPath()
				+ (request.getPathInfo() == null ? "" : request.getPathInfo());

		String HTTP_REFERER = request.getHeader("Referer");

		if (!checkRequestURIInNotFilterList(request)
				&& (username == null || StringUtils.isEmpty(HTTP_REFERER))) {
			response.addHeader("__timeout", "true");
			return;
		}

		filterChain.doFilter(servletRequest, servletResponse);
	}

	/**
	 * 销毁
	 */
	public void destroy() {
		notCheckURLList.clear();
	}

	/**
	 * 初始化过滤器
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		String notCheckURLListStr = filterConfig
				.getInitParameter("notCheckURLList");
		if (notCheckURLListStr != null) {

			String[] st = notCheckURLListStr.split(",");
			notCheckURLList.clear();
			for (String s : st) {
				notCheckURLList.add(s.trim());
			}
		}
	}

	private boolean checkRequestURIInNotFilterList(HttpServletRequest request) {
		boolean inNotFilterList = false;
		if (notCheckURLList.contains(uri)) {
			inNotFilterList = true;
		} else {
			for (String checkUrl : notCheckURLList) {
				if (RegexUtils.wildcardMatch(checkUrl, uri)) {
					inNotFilterList = true;
					break;
				}
			}
		}

		return inNotFilterList;
	}
}
